import numpy as np
import matplotlib

matplotlib.use(backend="TkAgg")
import matplotlib.pyplot as plt
import numpy.random as npr

'''
分布	     理论方差  (𝑏−𝑎)^2/12   模拟方差（200000样本）
U(0,10)	8.3333	   8.3307      非常接近
U(-5,5)	8.3333	   8.3232      也非常接近
'''
num_samples = 200000

dist1 = npr.uniform(0, 10, size=num_samples)
dist2 = npr.uniform(-5, 5, size=num_samples)

theoretical_var_1 = (10 - 0) ** 2 / 12
theoretical_var_2 = (5 - (-5)) ** 2 / 12

sample_var_1 = np.var(dist1)
sample_var_2 = np.var(dist2)

print("U(0,10): Theoretical Variance =", theoretical_var_1, ", Sample Variance =", sample_var_1)
print("U(-5,5): Theoretical Variance =", theoretical_var_2, ", Sample Variance =", sample_var_2)

x = np.linspace(0, 10, 500)
fx = np.ones_like(x) / 10  # uniform pdf
gx = x ** 2

plt.figure()
plt.plot(x, fx)
plt.title("PDF of U(0,10)")

plt.figure()
plt.plot(x, gx)
plt.title("g(x) = x^2 for LOTUS: E(X^2) = ∫ x^2 f(x) dx")

plt.show()
